<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRoute, useRouter, RouterView } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

import { isEmpty } from '../../utils/common.ts'
import { loginT, RegisterT } from '../../api/user.ts'
import { useUserStore } from '../../stores/index.ts'

const useUser = useUserStore()
const ruleFormRegister = ref<FormInstance>()
const ruleFormLogin = ref<FormInstance>()
const isRegister = ref(false) //是否展示注册

const goRegister = () => {
  isRegister.value = true
}
const goLogin = () => {
  isRegister.value = false
}

const checkUserName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户名'))
  }
  // 转换为字符串进行长度判断
  const strValue = value.toString()
  setTimeout(() => {
    // 检查是否是字符串
    if (typeof strValue !== 'string') {
      return callback(new Error('用户名必须是字符串'))
    }

    // 检查用户名长度
    if (strValue.length <= 5) {
      callback(new Error('用户名长度必须大于 5'))
    } else if (strValue.length >= 10) {
      callback(new Error('用户名长度必须小于 10'))
    } else {
      callback()
    }
  }, 1000)
}

const checkPhoneNumber = (rule: any, value: any, callback: any) => {
  if (isEmpty(value)) {
    callback(new Error('请输入手机号码'))
  }
}

const validatePass = (rule: any, value: any, callback: any) => {
  if (isEmpty(value)) {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.repassword !== '') {
      if (!ruleFormRegister.value) return
      ruleFormRegister.value.validateField('repassword')
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (isEmpty(value)) {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

let ruleForm = reactive({
  repassword: '',
  username: '',
  password: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  repassword: [{ validator: validatePass2, trigger: 'blur' }],
  username: [{ validator: checkUserName, trigger: 'blur' }],
  PhoneNumber: [{ validator: checkPhoneNumber, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!')
    }
  })
}

const register = async () => {
  await ruleFormRegister.value.validate()
  const res = await userRegisterService(ruleForm)
  console.log(res)

  ElMessage.success('注册成功')
  // 切换到登录
  isRegister.value = false
}
const router = useRouter()
const route = useRoute()
const goIndex = () => {
  router.push('/')
}

const login = async () => {
  await ruleFormLogin.value.validate()
  const params = reactive({
    username: ruleForm.username,
    password: ruleForm.password,
  })
  console.log(params)

  const res = await loginT(params)
  console.log(res.data)

  useUser.setToken(res.data.data)
  console.log(useUser.token)

  ElMessage.success('登录成功')
  goIndex()
}

watch(isRegister, (newValue, oldValue) => {
  Object.assign(ruleForm, {
    username: '',
    password: '',
    repassword: '',
  })
})
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-card style="max-width: 480px">
        <div class="LoginRegister">
          <div class="register" v-if="isRegister">
            <h2>注册</h2>
            <!-- <RouterView /> -->
            <el-form
              ref="ruleFormRegister"
              style="max-width: 600px"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="auto"
              class="demo-ruleForm"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username" placeholder="请输入用户名" />
              </el-form-item>
              <!-- <el-form-item label="手机号" prop="PhoneNumber">
                <el-input v-model.number="ruleForm.PhoneNumber" placeholder="请输入手机号码" />
              </el-form-item> -->
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="ruleForm.password"
                  type="password"
                  placeholder="请输入密码"
                  autocomplete="off"
                />
              </el-form-item>
              <!-- <el-form-item label="确认密码" prop="repassword">
                <el-input
                  v-model="ruleForm.repassword"
                  type="password"
                  placeholder="请再次输入密码"
                  autocomplete="off"
                />
              </el-form-item> -->

              <el-form-item class="bottomBtn" @click="register">
                <el-button type="primary" @click="submitForm(ruleFormRegister)"> 注册 </el-button>
              </el-form-item>
              <el-form-item>
                <el-link type="info" :underline="false" @click="goLogin"
                  >注册完成后点击
                  <p>登录 →</p>
                </el-link>
              </el-form-item>
            </el-form>
          </div>
          <div class="login" v-else>
            <h2>登录</h2>
            <!-- <RouterView /> -->
            <el-form
              ref="ruleFormLogin"
              style="max-width: 600px"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="auto"
              class="demo-ruleForm"
            >
              <el-form-item label="" prop="username">
                <el-input
                  v-model="ruleForm.username"
                  :prefix-icon="User"
                  placeholder="请输入用户名"
                />
              </el-form-item>

              <el-form-item label="" prop="password">
                <el-input
                  v-model="ruleForm.password"
                  type="password"
                  :prefix-icon="Lock"
                  placeholder="请输入密码"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item class="checkbox">
                <div class="checkbox">
                  <el-checkbox>记住我</el-checkbox>
                  <el-link type="primary" :underline="false">忘记密码？</el-link>
                </div>
              </el-form-item>

              <el-form-item class="bottomBtn" @click="login">
                <el-button type="primary" @click="submitForm(ruleFormLogin)"> 登录 </el-button>
              </el-form-item>
              <el-form-item>
                <el-link type="info" :underline="false" @click="goRegister"
                  >如果没有账号点击去
                  <p>注册 →</p>
                </el-link>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scope lang="scss">
.login-page {
  height: 100vh;

  background: url('../../assets/images/bgc.png') no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  .LoginRegister {
    padding: 15px;
    width: 380px;
    font-family: 'SimSun', '宋体', sans-serif, 15px;

    h2 {
      text-align: center;
      margin-bottom: 18px;
    }
    .el-form-item__content {
      justify-content: center;
    }
    .bottomBtn .el-form-item__content {
      justify-content: end;
    }
    .el-form-item {
      margin-bottom: 20px;
      font-size: 15px;
      align-items: center;
      .el-form-item__content {
        .el-input {
          height: 40px;
        }
      }
      .el-button--primary {
        --el-button-bg-color: #e60027;
        --el-button-border-color: #f60;
        font-size: 18px;
        width: 100%;
        height: 50px;
      }
      p {
        color: #e60027;
      }
    }
    .checkbox {
      display: flex;
      justify-content: space-between;
      margin-top: -8px;
      width: 100%;
    }
  }
}
</style>
